/* eslint-disable */

/**
 * 加载并引入模块
 * @param {string} scope 服务名
 * @param {string} module 子应用导出模块路径
 * @param {string} url 导出模块所属服务路径
 */
export const loadComponent = async (
  scope: string,
  module: string,
  url: string
): Promise<any> => {
  await dynamicScriptLoader.useDynamicScript(url);
  await __webpack_init_sharing__("default");

  // @ts-ignore
  const container = window[scope];

  // @ts-ignore
  await container.init(__webpack_share_scopes__.default);

  // @ts-ignore
  const factory = await container.get(module);
  return factory();
};

/**
 * 依次加载模块
 * @param {string} componentLoads 引入的模块数组
 */
export const remoteComponent = (
  componentLoads: Array<() => Promise<any>>
): Promise<Array<any>> => {
  return new Promise((resolve, reject) => {
    Promise.all(componentLoads.map((loadFn) => loadFn()))
      .then((res) => {
        resolve(res);
      })
      .catch((error) => {
        console.error("Failed to load one or more components:", error);
        reject(error);
      });
  });
};

const dynamicScriptLoader = {
  urlCache: new Set<string>(),

  useDynamicScript: (url: string): Promise<boolean> => {
    return new Promise((resolve, reject) => {
      if (!url) reject(false);

      if (dynamicScriptLoader.urlCache.has(url)) {
        resolve(true);
        return;
      }

      const element = document.createElement("script");
      // 防止微前端框架处理了该请求
      element.setAttribute("ignore", "true");
      element.async = true;
      element.type = "text/javascript";
      element.src = url;

      element.onload = () => {
        console.log("load:", url);
        dynamicScriptLoader.urlCache.add(url);
        resolve(true);
      };

      element.onerror = () => {
        reject(false);
      };

      document.head.appendChild(element);
    });
  },
};
